#!/bin/bash

version=4.66.0.zip

install_packages libfontconfig-dev || exit 0

"${DIRECTORY}/manage" install-if-not-installed Node.js || error "Failed to install Node.js! This is necessary to compile Boxy SVG."

#install asar and electron-packager
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"

wget -O /tmp/boxy-svg.zip "https://storage.boxy-svg.com/flathub/app-${version}" || exit 1

rm -rf /tmp/app
cd /tmp
unzip -q /tmp/boxy-svg.zip || error "Failed to extract!"
rm -f /tmp/boxy-svg.zip

cd /tmp/app
npm install || error "Failed to install npm dependencies!"
npm --prefix ./electron install || error "Failed to install npm dependencies in electron folder!"

if [ $arch == 32 ];then
  ./node_modules/.bin/electron-builder --armv7l
elif [ $arch == 64 ];then
  ./node_modules/.bin/electron-builder --arm64
else
  error "Failed to detect OS CPU architecture! Something is very wrong."
fi

#move to permanent folder
sudo rm -rf /opt/boxy-svg
sudo mv ./dist/linux-*-unpacked /opt/boxy-svg || error "Failed to move app files to /opt/boxy-svg!"

sudo mkdir -p /usr/local/share/icons
sudo cp ./metadata/com.boxy_svg.BoxySVG.svg /usr/local/share/icons
sudo cp ./metadata/com.boxy_svg.BoxySVG.png /usr/local/share/icons

cd $HOME
rm -rf /tmp/app

#create a terminal command to run Boxy without chrome sandbox for better performance
cat << "EOF" | sudo tee /usr/local/bin/boxy-svg >/dev/null
#!/bin/bash
/opt/boxy-svg/boxy-svg --no-sandbox "$@"
EOF
sudo chmod +x /usr/local/bin/boxy-svg

#remove broken mime association
if grep -qF 'image/svg+xml;application/illustrator=boxy-svg.desktop;' ~/.config/mimeapps.list ;then
  echo "$(grep -vF 'image/svg+xml;application/illustrator=boxy-svg.desktop;' ~/.config/mimeapps.list)" > ~/.config/mimeapps.list
fi

if ! grep -qF 'boxy-svg.desktop' ~/.config/mimeapps.list ;then
  echo "Associating the SVG mimetype with Boxy SVG..."
  echo "[Added Associations]
image/svg+xml=boxy-svg.desktop;
application/illustrator=boxy-svg.desktop;" >> ~/.config/mimeapps.list
  
fi

echo "[Desktop Entry]
Name=Boxy SVG
Comment=Scalable Vector Graphics (SVG) editor
Exec=boxy-svg %F
Icon=com.boxy_svg.BoxySVG
Type=Application
Terminal=false
Categories=Graphics
StartupWMClass=Boxy SVG
MimeType=image/svg+xml;image/png;image/jpeg;image/gif;image/webp;application/pdf;application/illustrator;
Keywords=SVG;Vector;Graphics;Editor;" | sudo tee /usr/share/applications/boxy-svg.desktop >/dev/null
